#!/usr/bin/env python

import sys
from download_manager_class import DownloadManager

def add_file ( liwe, name = "", descr = "", files_tags = "", id_file = 0, id_obj = 0, module = "", update = "", kwargs = 0 ):
	"""
	:INPUT:
		- name:					SAFE_DB_STRING
		- module:				SAFE_DB_STRING
		- descr:				SAFE_DB_STRING
		- files_tags:				SAFE_STRING
		- id_file : 				SAFE_NUMBER
		- id_obj :	 			SAFE_NUMBER
		- update: 				SAFE_DB_STRING

	:XPERMS:
		- upload, edit
	"""

	#sys.stderr.write ( "\n\n\n***** KEYS: %s\n\n" % liwe.pyhp.uploads.keys () )
	
	dm = DownloadManager ( liwe )

	if name: name = name.replace ( "'", "" )

	if not update:	
		keys = liwe.pyhp.uploads.keys ()
		if not keys:
			liwe.err_code = 101
			liwe.err_descr = "Manca il file %s %s" % ( name, descr )
			return {}

		for key in keys:
			my_file = liwe.pyhp.uploads [ key ]
			dm.add_file ( file_obj = my_file , name = name , descr = descr, files_tags = files_tags, 
					id_file = id_file , id_obj = id_obj, module = module , update = update, kwargs = kwargs )

	if update:
		my_file = ''
		dm.add_file ( file_obj = my_file , name = name , descr = descr, files_tags = files_tags, 
				id_file = id_file , id_obj = id_obj, module = module , update = update, kwargs = kwargs )

	return { "res" : 'OK' }

def remove_file ( liwe, path_name = "", id_file = 0, id_obj = 0, module = "" ):
	"""
	:INPUT:
		- path_name: path to file		SAFE_DB_STRING
		- id_file :  file  id			SAFE_NUMBER
		- id_obj :  				SAFE_NUMBER
		- module : module name 			SAFE_DB_STRING

	:XPERMS:
		- delete
	"""
	dm = DownloadManager ( liwe )
	res = dm.remove_file ( path_name = path_name, id_file = id_file , id_obj = id_obj, module = module )
	return { "res" : res }

def edit_file ( liwe, id_file = 0, id_obj = 0, module = "", action = "", kwargs = 0 ):
	"""
	:INPUT:
		- id_file : record id			SAFE_NUMBER
		- id_obj : 				SAFE_NUMBER
		- module  				SAFE_DB_STRING
		- action : action to invoke   		SAFE_STRING

	:XPERMS:
		- edit 
	"""
	dm = DownloadManager ( liwe )
	res = dm.edit_file ( id_file = id_file, id_obj = id_obj, module = module, action = "", kwargs = kwargs )
	#sys.stderr.write ( "****************  EDIT FILE: %s\n" % res )
	return { "res" : res }
